#pragma once

#include <iostream>
#include <string>
#include <functional>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"

using func_t = std::function<std::string(const std::string &)>;

const int defaultfd = -1;

using namespace LogModule;

class UdpServer
{

public:
    // 回调函数
    UdpServer(uint16_t port, func_t func)
        : _sockfd(defaultfd),
          _port(port),
          _isrunning(false),
          _func(func)
    {
    }

    void Init()
    {
        //int socket(int domain, int type, int protocol);
        // 1.创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);//AF_INET IPv4网络协议 
        //SOCK_DGRAM：提供无连接的、不可靠的数据传输（UDP）
        //protocol通常设置为0，表示使用给定协议族和套接字类型的默认协议
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error!";
            exit(1);
        }

        LOG(LogLevel::INFO) << "creat socket success, sockfd : " << _sockfd;

        // 2.绑定socket信息，ip和端口
        // 子类 struct sockaddr_in
        struct sockaddr_in local;
        // 清零
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;

        // 本地->网络
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY; // inaddr_any
                                            // 父类 struct sockaddr
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind success, sockfd : " << _sockfd;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (s > 0)
            {
                // 网络 -> 主机
                int peer_port = ntohs(peer.sin_port);
                std::string peer_ip = inet_ntoa(peer.sin_addr);
                buffer[s] = 0;

                std::string result = _func(buffer);

                LOG(LogLevel::DEBUG) << "[" << peer_ip << ":" << peer_port << "]# " << buffer;

                // 发消息
                sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
    }
    ~UdpServer()
    {
    }

private:
    int _sockfd;
    uint16_t _port;
    bool _isrunning;
    // 回调函数
    func_t _func;
};